package com.stbu;

import com.stbu.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Controller
@SessionAttributes(names = {"regDate"},types = {User.class})
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/toReg")
    public String toReg() {
        return "reg";
    }

    @RequestMapping("/reg")
    public String reg(@RequestParam("username") String u1,
                      @RequestParam("pwd") String password, Model model) {
        User user = new User();
        user.setUsername(u1);
        user.setPassword(password);
        Date regDate = new Date();
        model.addAttribute("regDate",regDate);
        model.addAttribute("user",user);
        return "forward:toLogin";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return  "login";
    }

    @RequestMapping("/login")
    public ModelAndView login(@RequestParam("username") String ulogin, @RequestParam("pwd") String pLogin,
                              @SessionAttribute("user") User regUser,ModelAndView mView) {
        String msg = "";
        if(ulogin.equalsIgnoreCase(regUser.getUsername()) && pLogin.equalsIgnoreCase(regUser.getPassword())){
            msg = "登陆成功:注册与登录时用户名与密码一致";
        } else {
            msg = "登录失败：登陆时用户名或者密码与注册时的用户名或密码不匹配";
        }
        mView.addObject("msg",msg);
        mView.addObject("username",ulogin);
        mView.setViewName("result");

        return mView;

    }


}
